package com.hatricks.is.gld.work.transform;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hatricks.is.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @packageName: com.hatricks.transform
 * @className: ModelTransformUtils
 * @author: yanyuhui y568821795@outlook.com
 * @date: 2024-06-14 17:48
 * @description:
 */
@SuppressWarnings("all")
public class ModelTransformUtils {
    public static void main(String[] args) {
        //String path = "E:\desktop\模型数据\\成本指标分析-成本指标库-契约用例-契约勿动-工程1先归档";
        //String path = "E:\\desktop\\模型数据\\model";
        //String path = "E:\\desktop\\模型数据\\丽景名苑一期工程-8.13终稿_（指标积累）";
        //String productSource = "zbsq-web";
        //String productSource = "cost-zbsq-web";
        //String productSource = "sgcbcs2";
        //String productSource = "jstz";
        //saveToFile(loadModelDataToJson(FileUtil.readBytes(path)), path, productSource);
        // 生成模型地址 中台模型地址
        JSONObject json = JSONObject.parseObject(projectJson);
        String id = json.getString("_id");
        JSONObject idJSON = JSONObject.parseObject(id);
        System.out.println(String.format("bizdata/%s/%s/%s/%s/%s", json.get("enterpriseId"), json.getString("projectCode"), json.get("productSource"), idJSON.getString("$oid"), json.getString("description")));
    }

    public static void saveToFile(JSONObject jsonData, String path, String productSource) {
        // 创建文件对象·
        JSONObject modelJson = JSON.parseObject(IoUtil.readUtf8(FileUtil.getInputStream(FileUtil.file(ProductSource.getByProductSource(productSource).getPath()))));
        Document doc = buildXmlDocument(modelJson, jsonData);
        // 创建输出格式
        File file = FileUtil.touch(path + ".xml");
        OutputFormat format = OutputFormat.createPrettyPrint();// 有换行和缩进效果
        format.setEncoding("UTF-8");// 编码
        // 获得XMLWriter
        try {
            XMLWriter writer = new XMLWriter(Files.newOutputStream(file.toPath()), format);
            // 输出xml
            writer.write(doc);
            // 释放资源(这里会帮我们把FileOutputStream关闭)
            writer.close();
        } catch (Exception ignored) {

        }
    }


    /**
     * 生成xml数据
     */
    private static Document buildXmlDocument(JSONObject modelJson, JSONObject jsonData) {
        Document doc = DocumentHelper.createDocument();
        Element model = doc.addElement("model");
        model.addAttribute("productSource", modelJson.getJSONArray("productSource").get(0).toString());
        model.addAttribute("createTime", DateUtil.date().toString());
        JSONArray records = modelJson.getJSONArray("records");
        for (int i = 0; i < records.size(); i++) {
            JSONObject modelD = records.getJSONObject(i);
            String name = modelD.getString("name");
            Element tableElement = model.addElement(name);
            tableElement.addAttribute("name", name);
            tableElement.addAttribute("remark", modelD.getString("remark"));
            JSONArray arrayFields = modelD.getJSONArray("fields");
            Object jsonNode = jsonData.get(name);
            if (jsonNode instanceof JSONObject) {
                Element element = tableElement.addElement("record");
                assignRecord(((JSONObject) jsonNode), element, arrayFields);
            }
            if (jsonNode instanceof JSONArray) {
                JSONArray array = (JSONArray) jsonNode;
                for (int a = 0; a < array.size(); a++) {
                    Element element = tableElement.addElement("record");
                    assignRecord(array.getJSONObject(a), element, arrayFields);
                }
            }
        }
        return doc;
    }

    static void assignRecord(JSONObject json, Element element, JSONArray arrayFields) {
        for (int z = 0; z < arrayFields.size(); z++) {
            JSONObject jsonField = arrayFields.getJSONObject(z);
            String fieldName = jsonField.getString("fieldName");
            Object value = json.get(fieldName);
            if (value != null) {
                element.addAttribute(fieldName, value.toString());
            }
        }
    }

    @AllArgsConstructor
    @Getter
    public enum ProductSource {
        ZBSQ_WEB("zbsq-web", "C:\\work_space\\java_work_space\\public_utils\\infrastructure-s\\src\\main\\resources\\model\\zbsqWeb.json"),
        COST_ZBSQ_WEB("cost-zbsq-web", "C:\\work_space\\java_work_space\\public_utils\\infrastructure-s\\src\\main\\resources\\model\\zbsqCost.json"),
        SGCBSC("sgcbcs2", "C:\\work_space\\java_work_space\\public_utils\\infrastructure-s\\src\\main\\resources\\model\\sgcbcs.json"),
        JSTZ("jstz", "C:\\work_space\\java_work_space\\public_utils\\infrastructure-s\\src\\main\\resources\\model\\jstz.json"),
        ;
        private final String productSource;
        private final String path;

        public static ProductSource getByProductSource(String productSource) {
            for (ProductSource productSourceEnum : ProductSource.values()) {
                if (productSourceEnum.getProductSource().equals(productSource)) {
                    return productSourceEnum;
                }
            }
            throw new BusinessException("当前不支持的模型");
        }
    }


    public static JSONObject loadModelDataToJson(byte[] modelContent) {
        if (modelContent == null || modelContent.length == 0) {
            return null;
        }
        // 从压缩流读取
        try (ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(modelContent))) {
            Map<String, String> contentItems = new HashMap<>();
            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] b = new byte[4096];
                int len;
                while ((len = zin.read(b)) > 0) {
                    out.write(b, 0, len);
                }

                contentItems.put(entry.getName(), out.toString());
                entry = zin.getNextEntry();
            }

            StringBuilder bizContent = new StringBuilder();
            if (contentItems.containsKey("metadata")) {
                bizContent.append(contentItems.get("model"));
            } else {
                bizContent.append("{");
                for (String name : contentItems.keySet()) {
                    String entryData = contentItems.get(name);
                    String entryContent = String.format("\"%s\":%s", name, entryData);
                    bizContent.append(entryContent);
                    bizContent.append(",");
                }
                bizContent.append("}");
            }
            zin.close();
            return JSONObject.parseObject(bizContent.toString());

        } catch (Exception e) {
            return null;
        }
    }


    public static final String projectJson = "{\n" +
            "  \"_id\":{\n" +
            "    \"$oid\":\"68f5d4977188ce3c70bf0f40\"\n" +
            "  },\n" +
            "  \"fileDescription\":\"工程2：2级结构-末级专业工程-工程2-2个单位工程-先归档的工程_上传_上传_副本\",\n" +
            "  \"productSource\":\"sgcbcs2\",\n" +
            "  \"bizFileType\":\"project\",\n" +
            "  \"sourceinfo\":{\n" +
            "    \"newType\":\"bq\",\n" +
            "    \"estiType\":\"1\",\n" +
            "    \"templateVersion\":\"2.1.3.11\",\n" +
            "    \"type\":\"local\",\n" +
            "    \"key\":\"gbq/est11-3/02e4f2583c834ad88227f64bcb8f0aa7/2级结构-末级专业工程-工程2-2个单位工程.GBQ6\"\n" +
            "  },\n" +
            "  \"gldUserId\":\"7155370729997865295\",\n" +
            "  \"data\":{\n" +
            "    \"auditFlowStatus\":1,\n" +
            "    \"fileDescription\":\"工程2：2级结构-末级专业工程-工程2-2个单位工程-先归档的工程_上传_上传_副本\",\n" +
            "    \"sourceinfo\":{\n" +
            "      \"newType\":\"bq\",\n" +
            "      \"estiType\":\"1\",\n" +
            "      \"templateVersion\":\"2.1.3.11\",\n" +
            "      \"type\":\"local\",\n" +
            "      \"key\":\"gbq/est11-3/02e4f2583c834ad88227f64bcb8f0aa7/2级结构-末级专业工程-工程2-2个单位工程.GBQ6\"\n" +
            "    },\n" +
            "    \"contractInfo\":{\n" +
            "      \"districtCode\":\"510116\",\n" +
            "      \"cityCode\":\"510100\",\n" +
            "      \"productPositioning\":\"高档\",\n" +
            "      \"projectType\":\"\",\n" +
            "      \"cityId\":\"322\",\n" +
            "      \"title\":\"末级专业校验成本指标工程土建工程\",\n" +
            "      \"contractInfoFields\":\"{\\\"CTI_项目名称\\\":\\\"XMSC2509290002\\\",\\\"CTI_编制时间\\\":\\\"\\\",\\\"CTI_使用功能\\\":\\\"\\\",\\\"CTI_单位编码\\\":\\\"\\\",\\\"CTI_檐高\\\":\\\"\\\",\\\"CTI_测试\\\":\\\"\\\"}\",\n" +
            "      \"orgId\":\"\",\n" +
            "      \"organizationId\":\"610291175862784\",\n" +
            "      \"projectCategoryName\":\"建筑工程\",\n" +
            "      \"cityName\":\"成都\",\n" +
            "      \"projectCode\":\"XMSC2509290002\",\n" +
            "      \"projectScaleUnit\":\"m2\",\n" +
            "      \"costType\":\"估算价\",\n" +
            "      \"startTime\":\"2025-09-29\",\n" +
            "      \"id\":\"4750907357489625312\",\n" +
            "      \"constructionUnit\":\"213\",\n" +
            "      \"districtName\":\"双流区\",\n" +
            "      \"organizationName\":\"国际化  研发部\",\n" +
            "      \"provinceCode\":\"510000\",\n" +
            "      \"projectCategoryCode\":\"001\",\n" +
            "      \"provinceId\":\"26\",\n" +
            "      \"districtId\":\"2738\",\n" +
            "      \"projectAddress\":\"四川/成都/双流区\",\n" +
            "      \"endTime\":\"2025-09-29\",\n" +
            "      \"enterpriseId\":\"6537227414530929606\",\n" +
            "      \"provinceName\":\"四川\",\n" +
            "      \"projectName\":\"yu新建项目\",\n" +
            "      \"dataSource\":\"WEB_ADD\",\n" +
            "      \"projectScale\":\"123123\",\n" +
            "      \"needNotify\":\"false\"\n" +
            "    },\n" +
            "    \"isGeps\":false,\n" +
            "    \"projectType\":\"file\",\n" +
            "    \"tb_region\":\"BeiJing\",\n" +
            "    \"templateId\":\"67231e9bf786b9190061a996\",\n" +
            "    \"type\":\"cs\",\n" +
            "    \"userID\":\"7155370729997865295\",\n" +
            "    \"tbbjAmount\":\"858812.95\",\n" +
            "    \"addendumVersion\":0,\n" +
            "    \"projectInfo\":{},\n" +
            "    \"targetState\":\"BH\",\n" +
            "    \"tbSummaryTotal\":\"858812.95\",\n" +
            "    \"archiveVersion\":1,\n" +
            "    \"id\":\"82be4830-5f51-4ce1-8eb2-279d6e875b78\",\n" +
            "    \"modifyVersion\":231,\n" +
            "    \"state\":\"normal\",\n" +
            "    \"auditSendVersionInfo\":[\n" +
            "      {\n" +
            "        \"nodeName\":\"编制人\",\n" +
            "        \"nodeId\":\"starter\",\n" +
            "        \"taskId\":\"c3fa0e2b-ad7c-11f0-af22-fa163eaec9b4\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"nodeName\":\"竞争审批\",\n" +
            "        \"nodeId\":\"Activity_0kdynwy\",\n" +
            "        \"taskId\":\"c40eceb4-ad7c-11f0-af22-fa163eaec9b4\"\n" +
            "      }\n" +
            "    ],\n" +
            "    \"create_time\":\"2025-10-20 14:19:06\",\n" +
            "    \"bidClassificationID\":\"北京13清单计价规范(增值税)(新)\",\n" +
            "    \"customPlugins\":[],\n" +
            "    \"lRL\":\"0.8732\",\n" +
            "    \"isNewCreateStandFile\":false,\n" +
            "    \"folderId\":\"root\",\n" +
            "    \"isCompleteRate\":false,\n" +
            "    \"calFundation\":\"中标预算清单\",\n" +
            "    \"softversion\":\"3.1.1.5\",\n" +
            "    \"normDBSeriesID\":\"BJ2012\",\n" +
            "    \"shareToInfo\":[],\n" +
            "    \"updateInfo\":{},\n" +
            "    \"gldUserId\":\"7155370729997865295\",\n" +
            "    \"description\":\"2级结构-末级专业工程-工程2-2个单位工程\",\n" +
            "    \"total\":\"108939.98\",\n" +
            "    \"compareInfo\":[\n" +
            "      {\n" +
            "        \"data\":\"est-archive/2025-10-20/82be4830-5f51-4ce1-8eb2-279d6e875b78/1/data.data\",\n" +
            "        \"project\":\"est-archive/2025-10-20/82be4830-5f51-4ce1-8eb2-279d6e875b78/1/project.json\",\n" +
            "        \"version\":1\n" +
            "      }\n" +
            "    ],\n" +
            "    \"estShareToInfo\":[],\n" +
            "    \"industryType\":\"building\",\n" +
            "    \"estShareFromInfo\":[],\n" +
            "    \"projectCode\":\"XMSC2509290002\",\n" +
            "    \"subjectCatalogID\":\"daedb924e2ec4678a599ca970d66ed4e\",\n" +
            "    \"estiType\":\"1\",\n" +
            "    \"projectProfit\":\"87.32%\",\n" +
            "    \"archiveInfo\":{\n" +
            "      \"stage\":\"target\",\n" +
            "      \"isHistoryProject\":true,\n" +
            "      \"toArchiveTime\":\"2025-10-20\"\n" +
            "    },\n" +
            "    \"csMode\":\"targetCS\",\n" +
            "    \"integrationInfo\":{},\n" +
            "    \"sourceBQInfo\":{\n" +
            "      \"isBakBQItemRate\":false,\n" +
            "      \"isSourceBQCreate\":false\n" +
            "    },\n" +
            "    \"cbzj\":\"108940.05\",\n" +
            "    \"lastModify\":\"2025-10-20 14:20:05\",\n" +
            "    \"isMergeEdit\":false,\n" +
            "    \"oldSoftVersion\":\"3.1.1.5\",\n" +
            "    \"tb_total\":\"858812.95\",\n" +
            "    \"enterpriseId\":\"6537227414530929606\",\n" +
            "    \"fileType\":\"gbq_bq\",\n" +
            "    \"shareFromInfo\":[]\n" +
            "  },\n" +
            "  \"projectType\":\"file\",\n" +
            "  \"tb_region\":\"BeiJing\",\n" +
            "  \"description\":\"工程2：2级结构-末级专业工程-工程2-2个单位工程-先归档的工程_上传_上传_副本\",\n" +
            "  \"pid\":null,\n" +
            "  \"type\":\"cs\",\n" +
            "  \"folderPath\":\"\",\n" +
            "  \"industryType\":\"building\",\n" +
            "  \"projectCode\":\"XMSC2509290002\",\n" +
            "  \"archiveUpdateTime\":\"2025-10-20 14:20:06\",\n" +
            "  \"archiveDate\":\"2025-10-20 14:20:06\",\n" +
            "  \"csMode\":\"targetCS\",\n" +
            "  \"id\":\"68f5d4977188ce3c70bf0f40a\",\n" +
            "  \"bizFileCategoryId\":\"65dfdef296742c82d58773bd\",\n" +
            "  \"create_time\":\"2025-10-20 14:20:06\",\n" +
            "  \"lastModify\":\"2025-10-20 14:20:06\",\n" +
            "  \"edit_time\":\"2025-10-20 14:20:06\",\n" +
            "  \"userName\":\"7155370729997865295\",\n" +
            "  \"intact\":true,\n" +
            "  \"stage\":\"目标成本测算\",\n" +
            "  \"createTime\":\"2025-10-20 14:20:06\",\n" +
            "  \"projectAddress\":\"四川/成都/双流区\",\n" +
            "  \"dataStore\":\"OSS\",\n" +
            "  \"enterpriseId\":\"6537227414530929606\",\n" +
            "  \"projectName\":\"yu新建项目\",\n" +
            "  \"projectId\":\"82be4830-5f51-4ce1-8eb2-279d6e875b78\",\n" +
            "  \"getUploadPath\":true,\n" +
            "  \"isEmpty\":false\n" +
            "}";

}
